package com.gxust.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.gxust.mapper.CartMapper;
import com.gxust.pojo.Cart;
import com.gxust.pojo.PageBean;
import com.gxust.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;
    @Override
    public void add(Cart cart) {
        // 拿出 cart 里面的有用数据
        Integer userId = Objects.requireNonNull(cart.getUserId());
        Integer productId = Objects.requireNonNull(cart.getProductId());
        Integer quantity = Objects.requireNonNull(cart.getQuantity());

        // 查询有无数据
        Cart existingCart = cartMapper.cartList(userId, productId);

        if (existingCart != null) {
            // 若有数据，进行更新操作
            Integer cartId = existingCart.getCartId();
            cartMapper.update(cartId, existingCart.getQuantity() + quantity);
        } else {
            cartMapper.insert(cart);
        }
    }


    @Override
    @Transactional // 开启事务管理
    public PageBean page(Integer page, Integer pageSize, Integer id) {
        //1. 设置分页参数
        PageHelper.startPage(page, pageSize);
        //2. 执行查询
        List<Map<String, Object>> cartList = cartMapper.list(id);
        Page<Map<String, Object>> p = (Page<Map<String, Object>>) cartList;
        //3. 封装PageBean对象
        return new PageBean(p.getTotal(), p.getResult());
    }

    @Override
    public void del(Integer id) {
        cartMapper.del(id);
    }

    @Override
    public void update(Cart cart) {
        // 拿出 cart 里面的有用数据
        Integer userId = Objects.requireNonNull(cart.getUserId());
        Integer productId = Objects.requireNonNull(cart.getProductId());
        Integer quantity = Objects.requireNonNull(cart.getQuantity());

        // 查询有无数据
        Cart existingCart = cartMapper.cartList(userId, productId);
        // 若有数据，进行更新操作
        Integer cartId = existingCart.getCartId();
        cartMapper.update(cartId, quantity);

    }

    @Override
    public Map<String, Object> CartInfoById(Integer id, Integer productId) {
        return cartMapper.getCartById(id,productId);
    }


}
